import axios from 'axios'
import { Message } from 'element-ui'

import store from '@/store'

const service = axios.create({
  baseURL: process.env.API_BASE_URL,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    if (!config.noLoading) {
      store.dispatch('setLoading', true)
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (!response.config.noLoading) {
      store.dispatch('setLoading', false)
    }
    return response
  },
  error => {
    store.dispatch('setLoading', false)
    Message({
      type: 'error',
      message: error.message,
      duration: 3000
    })
  }
)

export default service
